package org.study.stream;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * parallelStream() 示例
 * 参考 https://qa.1r1g.com/sf/ask/2816666961
 *
 * @author Administrator
 * @date 2023-01-03
 */
public class StreamTest09 {
    public static void main(String[] args) throws InterruptedException {
        testWithBug();
        test01();
        test02();
        test03();
    }

    public static void testWithBug() {
        List<Integer> list = IntStream.range(0, 10000).boxed().collect(Collectors.toList());
        Map<Integer, Integer> map = new HashMap<>();
        list.parallelStream().forEach(i -> {
            map.put(i, i);
        });
        System.out.println("list.size()=" + list.size() + "，map.size()=" + map.size());
    }

    public static void test01() {
        List<Integer> list = IntStream.range(0, 10000).boxed().collect(Collectors.toList());
        Map<Integer, Integer> map = new HashMap<>();
        list.stream().forEach(i -> {
            map.put(i, i);
        });
        System.out.println("list.size()=" + list.size() + "，map.size()=" + map.size());
    }

    public static void test02() {
        List<Integer> list = IntStream.range(0, 10000).boxed().collect(Collectors.toList());
        Map<Integer, Integer> map = list.parallelStream().collect(Collectors.toMap(i -> i, i -> i));
        System.out.println("list.size()=" + list.size() + "，map.size()=" + map.size());
    }

    public static void test03() {
        List<Integer> list = IntStream.range(0, 10000).boxed().collect(Collectors.toList());
        Map<Integer, Integer> map = new ConcurrentHashMap<>();
        list.parallelStream().forEach(i -> {
            map.put(i, i);
        });
        System.out.println("list.size()=" + list.size() + "，map.size()=" + map.size());
    }
}
